package com.second.app.thread.线程基础.day07.线程通信.实战.换一个写法;

import org.apache.commons.lang3.StringUtils;

/**
 * @Author GYZ
 * @Date 2023/11/30
 * <pre>
 *
 * </pre>
 */

class Variable {

    public static String value = "";
}

public class Run {

    public static void main(String[] args) {

        class BlackThread extends Thread {
            private final Object lock;

            public BlackThread(Object lock) {
                this.lock = lock;
            }

            @Override
            public void run() {
                try {
                    synchronized (lock) {
                        while (!StringUtils.isEmpty(Variable.value)) {
                            lock.wait();
                        }
                        for (int i = 0; i < 5; i++) {
                            System.out.println("★★★★★★★★");
                        }
                        Variable.value = "123";
                        lock.notifyAll();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        class WhiteThread extends Thread {
            private final Object lock;

            public WhiteThread(Object lock) {
                this.lock = lock;
            }

            @Override
            public void run() {
                try {
                    synchronized (lock) {
                        while (StringUtils.isEmpty(Variable.value)) {
                            lock.wait();
                        }
                        for (int i = 0; i < 5; i++) {
                            System.out.println("☆☆☆☆☆☆☆☆");
                        }
                        Variable.value = "";
                        lock.notifyAll();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        Object lock = new Object();

        for (int i = 0; i < 5; i++) {
            BlackThread blackThread = new BlackThread(lock);
            blackThread.start();
            WhiteThread whiteThread = new WhiteThread(lock);
            whiteThread.start();

        }
    }
}
